package com.sunnyebuy.merchant.action;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.sunnyebuy.merchant.SystemConfig;
import com.sunnyebuy.merchant.po.Merchant;
import com.sunnyebuy.merchant.service.MerchantService;
import com.sunnyebuy.merchant.util.CommonUtil;

/**
 * <p>
 * Title: MerchantAction.java
 * </p>
 * 
 * <p>
 * Description: com.sunnyebuy.merchant.action
 * </p>
 * 
 * <p>
 * Copyright: Copyright (c) 2008-2011 All rights reserved.
 * </p>
 * 
 * <p>
 * Created: 2011-12-28 上午11:05:14
 * </p>
 * 
 * @author Wenzhong Gu
 * 
 * @version 1.0
 */
@Controller(value = "merchantAction")
@Scope(value = "prototype")
public class MerchantAction extends MerchantBaseAction {

	private static final long serialVersionUID = -4286884910955806072L;
	private static final Logger log = LoggerFactory.getLogger(MerchantAction.class);
	private Merchant merchant;
	private String validcode;

	@Resource
	private MerchantService merchantService;

	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "merchant.merchantEmail", key = "email.required"),
			@RequiredStringValidator(fieldName = "merchant.merchantPassword", key = "password.required"),
			@RequiredStringValidator(fieldName = "validcode", key = "validcode.required") }, stringLengthFields = {
			@StringLengthFieldValidator(fieldName = "merchant.merchantEmail", minLength = "6", maxLength = "20", key = "email.length.limit"),
			@StringLengthFieldValidator(fieldName = "merchant.merchantPassword", minLength = "6", maxLength = "20", key = "password.length.limit") }, emails = { @EmailValidator(fieldName = "merchant.merchantEmail", key = "email.format.invalid") })
	public String register() {
		String email = merchant.getMerchantEmail();
		String password = merchant.getMerchantPassword();
		Merchant m = merchantService.findMerchantByEmail(email);
		if (m != null) {
			this.addActionError(getText("username.password.mismatch"));
			return INPUT;
		} else {
			String encode = CommonUtil.md5(email + password);
			merchant.setMerchantPassword(encode);
			try {
				merchantService.addMerchant(merchant);
			} catch (Exception e) {
				log.error(e.getMessage());
			}
			return SUCCESS;
		}
	}

	@SuppressWarnings("rawtypes")
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "merchant.merchantEmail", key = "email.required"),
			@RequiredStringValidator(fieldName = "merchant.merchantPassword", key = "password.required") }, stringLengthFields = {
			@StringLengthFieldValidator(fieldName = "merchant.merchantEmail", minLength = "6", maxLength = "20", key = "email.length.limit"),
			@StringLengthFieldValidator(fieldName = "merchant.merchantPassword", minLength = "6", maxLength = "20", key = "password.length.limit") }, emails = { @EmailValidator(fieldName = "merchant.merchantEmail", key = "email.format.invalid") })
	public String login() {
		String email = merchant.getMerchantEmail();
		String password = merchant.getMerchantPassword();
		String validcode = (String) getRequest().getSession().getId();
		String parm = (String) getRequest().getParameter("validcode");
		if (validcode != null && validcode.equalsIgnoreCase(parm)) {
			String encodeEmail = CommonUtil.md5(email + password);
			Merchant merchant = merchantService.findMerchant(email, encodeEmail);
			if (merchant != null) {
				// 防止Session Fixation攻击，重新生成session
				HttpSession httpSession = getRequest().getSession();
				Enumeration enumeration = httpSession.getAttributeNames();
				Map<String, Object> sessionMap = new HashMap<String, Object>();
				while (enumeration.hasMoreElements()) {
					String key = (String) enumeration.nextElement();
					sessionMap.put(key, httpSession.getAttribute(key));
				}
				httpSession.invalidate();
				httpSession = getRequest().getSession(true);
				for (String key : sessionMap.keySet()) {
					Object value = sessionMap.get(key);
					httpSession.setAttribute(key, value);
				}
				// 写入merchant登录Session
				httpSession.setAttribute(SystemConfig.MERCHANT_ID_SESSION_NAME, merchant.getMerchantId());
				setCookie(SystemConfig.MERCHANT_USERNAME_COOKIE_NAME, merchant.getMerchantId());
			}
			return SUCCESS;
		} else {// 验证吗不正确
			addActionError(getText("validcode.error"));
			return INPUT;
		}
	}

	public Merchant getMerchant() {
		return merchant;
	}

	public void setMerchant(Merchant merchant) {
		this.merchant = merchant;
	}

	public String getValidcode() {
		return validcode;
	}

	public void setValidcode(String validcode) {
		this.validcode = validcode;
	}
}